package com.powermgr.boringtest.utils;

import com.alibaba.fastjson.JSON;
import com.powermgr.boringtest.bean.PrData;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * ReadWriteUtils
 *
 * @author qiuxiangdong
 * @date 2023/6/12
 */
public class ReadWriteUtils {
    public static String getCurrentTime(){
        Date currentTime = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        return format.format(currentTime);
    }
    public static String getPrTime(){
        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return dateFormat.format(date);
    }
    public static List<PrData> readArchivePrFile() throws IOException {
        ArrayList<PrData> prList = new ArrayList<>();
        File dirFile = new File(ConfigUtils.PR_3DAY);
        String[] fileList = dirFile.list();
        if (fileList != null) {
            for (String string : fileList) {
                File file = new File(dirFile.getPath(), string);
                String name = file.getName();
                if (!file.isDirectory()) {
                    PrData access = JSON.parseObject(readFile(ConfigUtils.PR_3DAY + File.separator + name), PrData.class);
                    prList.add(access);
                }
            }
        }
        return prList;
    }
    public static String readFile(String jsonFile) throws IOException {
        Path file = Paths.get(jsonFile);
        if (!Files.exists(file)){
            throw new IOException(file + "文件不存在");
        }
        return FileUtils.readFileToString(file.toFile(), StandardCharsets.UTF_8);
    }
    public static void writeFile(String jsonFile, String data) throws IOException {
        Path file = Paths.get(jsonFile);
        if (!Files.exists(file)){
            Files.createFile(file);
        }
        FileUtils.writeStringToFile(file.toFile(), data, StandardCharsets.UTF_8);
    }
}
